-module(ddc_util).

-compile(export_all).
-include("ddc_settings.hrl").

%% split/1 - Split string to words according to regexp (from settings).
split(String) ->
    split(String, ?SPLIT_REGEXP).

split(String, Regexp) ->
    Result = re:split(string:to_lower(String), Regexp, [{return, list},unicode]),
    case Result of
	nomatch -> [String];
	_ -> lists:filter(fun(Elem) -> (Elem=/=[]) and (Elem=/=" ") end, Result)
    end.

%% Make an actual string from generated array of words
%% @TODO Capitalize sentences.
post_process(Sentence) ->
    F_c =fun(W, {Prev, Acc}) ->
		 Cap=lists:member(Prev, ?SEN_END),
		 {W, [if
			  Cap -> capitalize(W);
			  true -> W
		      end|Acc]}
	 end,
    F_sp=fun(W, {Prev, Acc}) ->
		 Space=not(lists:member(W, ?NOSPACE_AFTER) or lists:member(Prev, ?NOSPACE_BEFORE)),
		 if
		     Space ->
			 {W, [W, " "|Acc]};
		     true -> {W, [W|Acc]}
		 end
	 end,
    {_, L_c}=lists:foldl(F_c, {start, []}, tl(lists:sublist(Sentence, length(Sentence)-1))),
    {_, L}=lists:foldr(F_sp, {[], []}, lists:reverse(L_c)),     
    lists:flatten(L).

to_upper(char, 1105) ->
    1025;
to_upper(char, C) when C>1071 andalso C<1104 ->
    C-32;
to_upper(char, C) ->
    string:to_upper(C).

to_upper(String) ->
    lists:map(fun(C) -> to_upper(char, C) end, String).

capitalize([C|Rest]) ->
    [to_upper(char, C)|Rest].

to_lower(char, 1025) ->
    1105;
to_lower(char, C) when C>1039 andalso C<1072 ->
    C+32;
to_lower(char, C) -> string:to_lower(C).

to_lower(String) ->
    lists:map(fun(C) -> to_lower(char, C) end, String).
		      
